//
//  UIView+TYEmptyView.m
//  TYUIKit
//
//  Created by TuyaInc on 2019/5/21.
//

#import "UIView+TYEmptyView.h"

#import <objc/runtime.h>

#import "TYEmptyBaseView+Internal.h"

@implementation UIView (TYEmptyView)

#pragma mark - Accessor
- (void)setTy_emptyView:(__kindof TYEmptyBaseView *)ty_emptyView {
    objc_setAssociatedObject(self, @selector(ty_emptyView), ty_emptyView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (TYEmptyBaseView *)ty_emptyView {
    return objc_getAssociatedObject(self, _cmd);
}

#pragma mark - Public
- (void)ty_showOrHideEmptyView:(BOOL)isShow{
    if (isShow) {
        [self ty_showEmptyView:YES];
    }
    else{
        [self ty_hideEmptyView:YES];
    }
}

- (void)ty_showEmptyView:(BOOL)animate {
    TYEmptyBaseView *emptyView = self.ty_emptyView;
    if (!emptyView) {
        return;
    }
    if (emptyView.superview != self) {
        emptyView.alpha = 0;
        [self insertSubview:emptyView atIndex:0];
        if ([emptyView respondsToSelector:@selector(ty_emptyViewDidAddToSuperView)]) {
            [emptyView ty_emptyViewDidAddToSuperView];
        }
    }
    if ([emptyView respondsToSelector:@selector(ty_emptyViewShouldLayout)]) {
        [emptyView ty_emptyViewShouldLayout];
    }
    if ([emptyView respondsToSelector:@selector(ty_emptyViewWillShow)]) {
        [emptyView ty_emptyViewWillShow];
    }
    
    if (animate && [emptyView respondsToSelector:@selector(ty_emptyViewShowAnimation:)]) {
        __weak typeof(emptyView) weakEmptyVew = emptyView;
        [emptyView ty_emptyViewShowAnimation:^(BOOL finished) {
            weakEmptyVew.isShowing = YES;
            if ([weakEmptyVew respondsToSelector:@selector(ty_emptyViewDidShow)]) {
                [weakEmptyVew ty_emptyViewDidShow];
            }
        }];
    } else {
        emptyView.alpha = 1;
        emptyView.isShowing = YES;
        if ([emptyView respondsToSelector:@selector(ty_emptyViewDidShow)]) {
            [emptyView ty_emptyViewDidShow];
        }
    }
}

- (void)ty_hideEmptyView:(BOOL)animate {
    TYEmptyBaseView *emptyView = self.ty_emptyView;
    if (!emptyView) {
        return;
    }
    
    if ([emptyView respondsToSelector:@selector(ty_emptyViewWillHide)]) {
        [emptyView ty_emptyViewWillHide];
    }
    
    if (animate && [emptyView respondsToSelector:@selector(ty_emptyViewHideAnimation:)]) {
        __weak typeof(emptyView) weakEmptyView = emptyView;
        [emptyView ty_emptyViewHideAnimation:^(BOOL finished) {
            weakEmptyView.isShowing = NO;
            if ([weakEmptyView respondsToSelector:@selector(ty_emptyViewDidHide)]) {
                [emptyView ty_emptyViewDidHide];
            }
        }];
    } else {
        emptyView.alpha = 0;
        emptyView.isShowing = NO;
        if ([emptyView respondsToSelector:@selector(ty_emptyViewDidHide)]) {
            [emptyView ty_emptyViewDidHide];
        }
    }
}

@end
